import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hexcolor/hexcolor.dart';

/// 扩展 String
extension ExString on String {
  /// 生成 Color
  Color get toColor => HexColor(this);

  /// 生成Svg
  Widget toSvg({
    double? width,
    double? height,
    BoxFit fit = BoxFit.contain,
    Alignment alignment = Alignment.center,
    Color? color,
  }) =>
      SvgPicture.asset(
        this,
        width: width,
        height: height,
        fit: fit,
        alignment: alignment,
        colorFilter: color == null ? null : ColorFilter.mode(color, BlendMode.srcIn),
      );
}

extension ExNullString on String? {
  /// 返回默认字符串
  String getAuto(String hint) {
    return empty ? hint : this!;
  }

  /// 字符串是否为空
  bool get empty {
    return !notEmpty;
  }

  /// 字符串是否非空
  bool get notEmpty {
    return this != null && this!.isNotEmpty;
  }

  /// 字符串比较
  bool equals(String? temp) {
    if (empty) return false;
    if (temp.empty) return false;
    return this == temp;
  }

  /// 清除 html 标签
  String get clearHtml {
    if (empty) return '';
    return this!.replaceAll(RegExp(r'<[^>]*>'), '');
  }

  /// 转成加密手机号
  String get encryptPhone {
    if (empty) return '';
    if (this!.length < 7) return this!;
    return this!.replaceRange(3, 7, '****');
  }

  ///最多保留2位小数，直接截取，不四舍五入
  String get toMoney {
    double money = double.tryParse(this ?? '') ?? 0;
    return Decimal.parse(money.toString()).floor(scale: 2).toString();
  }
}

class CommonString {
  static String append(List<String> params, String append) {
    if (params.isEmpty) return "";
    String result = params.reduce((value, element) {
      if (element.notEmpty) {
        return value + append + element;
      }
      return value;
    });
    if (result.isNotEmpty && result.startsWith(append)) {
      result = result.substring(append.length, result.length);
    }
    return result;
  }
}
